package com.veo.service.Imp;

import com.github.pagehelper.PageHelper;
import com.veo.dao.UserDao;
import com.veo.domain.Role;
import com.veo.domain.UserInfo;
import com.veo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    //密码加密
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username!=null&&username!=""){
            UserInfo findUser = userDao.findUserByName(username);
            List<Role> roles = findUser.getRoles();
            List<SimpleGrantedAuthority> authoritys = getAuthority(roles);
            User user = new User(findUser.getUsername(),findUser.getPassword(), findUser.getStatus() == 0 ? false : true,
                    true, true, true, authoritys);
            return user;
        }else {
            return null;
        }
    }

    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> authoritys = new ArrayList();
        for (Role role : roles) {
            authoritys.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName().toUpperCase()));
        }
        return authoritys;
    }


    public List<UserInfo> findAllUser(int page,int size,String searcherName) {
        //实现分页
        PageHelper.startPage(page,size);
        return userDao.findAllUser(searcherName);
    }

    public int addUser(UserInfo userInfo) {
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        return userDao.addUser(userInfo);
    }

    public UserInfo findUserById(String id) {
        return userDao.findUserById(id);
    }

    public List<Role> findOtherRole(String userId) {
        return userDao.findOtherRole(userId);
    }

    public int addRoleToUser(String userId, String[] roleId) {
        int count=0;
        for (String id : roleId) {
            count=userDao.addRoleToUser(userId,id);
        }
        return count;
    }

    public int deleteUserRoleId(String id) {
        return userDao.deleteUserRoleId(id);
    }

    public int deleteUserById(String id) {
        return userDao.deleteUserById(id);
    }
}